package com.sdhs.paas.authserver.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sdhs.paas.authserver.entity.UserInfo;
import com.sdhs.paas.authserver.service.AuthService;
import com.sdhs.paas.authserver.service.UserService;
import com.sdhs.paas.authserver.util.user.JwtAuthenticationRequest;
import com.sdhs.paas.authserver.util.user.JwtTokenUtil;
import com.sdhs.paas.authshare.exception.auth.UserInvalidException;
import com.sdhs.paas.authshare.util.jwt.IJWTInfo;
import com.sdhs.paas.authshare.util.jwt.JWTInfo;

@Service
public class AuthServiceImpl implements AuthService{
	@Autowired
	private UserService userService;
	
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	
	@Override
	public String login(JwtAuthenticationRequest authenticationRequest) throws Exception {
		UserInfo userInfo = userService.validate(authenticationRequest);
		 if (!StringUtils.isEmpty(userInfo.getId())) {
			 return jwtTokenUtil.generateToken(new JWTInfo(userInfo.getUsername(), userInfo.getId() + "", userInfo.getName()));
		 }
		 throw new UserInvalidException("用户不存在或账户密码错误!");
	}

	@Override
	public String refresh(String oldToken) throws Exception {
		return jwtTokenUtil.generateToken(jwtTokenUtil.getInfoFromToken(oldToken));
	}

	@Override
	public IJWTInfo validate(String token) throws Exception {
		jwtTokenUtil.getInfoFromToken(token);
		IJWTInfo jwtInfo = jwtTokenUtil.getInfoFromToken(token);
    	return jwtInfo;
	}
	
	public UserInfo getUserInfo(String token) throws Exception{
		IJWTInfo jwtInfo = jwtTokenUtil.getInfoFromToken(token);
		UserInfo userInfo = new UserInfo();
		String userId = jwtInfo.getId();
		String name = jwtInfo.getName();
		String avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
		List<String> roles = userService.getRolesByUserId(userId);
		userInfo.setAvatar(avatar);
		userInfo.setName(name);
		userInfo.setId(userId);
		userInfo.setRoles(roles);
    	return userInfo;
	}

}
